import React, { useState, useRef, useEffect } from "react";
import "./css/ZpChat.scss";
import {
  NavBar,
  Form,
  Button,
  Card,
  Avatar,
  TextArea,
  Selector,
  Tabs,
  Mask,
  Toast,
  SpinLoading,
} from "antd-mobile";
import constant from "./common/Constants";
import util from "./common/Util";
import { useNavigate } from "react-router-dom";
import { CloseCircleOutline, AddOutline } from "antd-mobile-icons";
/**
 * 智谱
 * @returns
 */
function ZpChat() {
  const navigate = useNavigate();

  const updateSource = useRef("");
  const chatBoxRef = useRef();
  const uuid = util.guid();
  const [activeKey, setActiveKey] = useState(uuid);
  const tabCountRef = useRef(1);
  const textRef = useRef();
  const resultRef = useRef("");
  const [tabConfig, setTabConfig] = useState({
    [uuid]: {
      title: "对话1",
      key: uuid,
      sessionId: uuid,
      itemList: [],
    },
  });

  const back = () => {
    navigate("/menuList");
  };
  const addTab = (e) => {
    const uuid = util.guid();
    let keys = Object.keys(tabConfig);
    tabCountRef.current++;

    tabConfig[uuid] = {
      title: "对话" + tabCountRef.current,
      key: uuid,
      sessionId: uuid,
      itemList: [],
    };
    setTabConfig({ ...tabConfig });
    setActiveKey(uuid);
    e.stopPropagation();
  };
  const changeTab = (e) => {
    setActiveKey(e);
    console.info("切换tab,当前:" + e);
  };

  const closeTab = (key, event) => {
    let keys = Object.keys(tabConfig);
    if (keys.length == 1) {
      return;
    }
    delete tabConfig[key];
    keys = Object.keys(tabConfig);
    updateSource.current = "";
    setTabConfig({ ...tabConfig });
    setActiveKey(keys[keys.length - 1]);
    event.stopPropagation();
    return false;
  };
  const send = (o) => {
    let text = o.content;
    const item = {
      type: "right",
      text: text,
      role: "user",
    };
    const tab = tabConfig[activeKey];
    if (textRef.current) {
      textRef.current.clear();
    }
    tab.itemList = [...tab.itemList, item];
    updateSource.current = "send";
    setTabConfig({ ...tabConfig });
    let token = util.getToken();

    util.postForm(
      constant.baseUrl + "/app/zpChat",
      { token, text },
      (resultObj) => {
        if (resultObj.code === 50002) {
          localStorage.removeItem("token");
          navigate("/login");
        }
        if (resultObj.code === 0) {
          const resp = resultObj.resp;
          const respItem = {
            type: "left",
            text: resp,
            role: "assistant",
          };
          tab.itemList = [...tab.itemList, respItem];
          setTabConfig({ ...tabConfig });
        } else {
          Toast.show({
            content: "信息:" + resultObj.message,
            position: "top",
          });
        }
      }
    );
  };

  const send2 = (o) => {
    let text = o.content;
    const item = {
      type: "right",
      text: text,
      role: "user",
    };
    const tab = tabConfig[activeKey];
    if (textRef.current) {
      textRef.current.clear();
    }
    tab.itemList = [...tab.itemList, item];
    updateSource.current = "send";
    setTabConfig({ ...tabConfig });
    let token = util.getToken();
    resultRef.current = "";
    const es = new EventSource(
      constant.baseUrl + "/app/zhiPuChatBySSE?text=" + text + "&token=" + token
    );
    es.onmessage = (e) => {
      let o = JSON.parse(e.data);
      if (o.type === "add") {
        resultRef.current += o.data;
        if (o.first) {
          const respItem = {
            type: "left",
            text: resultRef.current,
            role: "assistant",
          };
          tab.itemList = [...tab.itemList, respItem];
        } else {
          let item = tab.itemList[tab.itemList.length - 1];
          item.text = resultRef.current;
        }
        setTabConfig({ ...tabConfig });
      }
    };
    es.onerror = (error) => {
      console.info("error", error);
      if (error.currentTarget.readyState === EventSource.CLOSED) {
        console.log("连接关闭");
      }
      es.close();
    };
  };

  useEffect(() => {
    if (updateSource.current === "send") {
      if (chatBoxRef.current) {
        chatBoxRef.current.scrollTop = chatBoxRef.current.scrollHeight;
      }
    }
  }, [tabConfig]);

  return (
    <div  className="ZpChat container">
      <NavBar onBack={back} style={{ "--border-bottom": "1px #eee solid" }}>
        智谱对话
      </NavBar>
      <div>
        <Tabs stretch={false} activeKey={activeKey} onChange={changeTab}>
          {Object.keys(tabConfig).map((key) => {
            let tab = tabConfig[key];
            return (
              <Tabs.Tab
                key={tab.key}
                title={
                  <div>
                    {tab.title}
                    <span
                      onClick={closeTab.bind(this, tab.key)}
                      style={{ paddingLeft: "10px", display: "inline-block" }}
                    >
                      <CloseCircleOutline fontSize={18} />
                    </span>
                  </div>
                }
              >
                <div className="chat-box" ref={chatBoxRef}>
                  {tab.itemList.length === 0 && (
                    <div>{tab.title}提交内容开启对话</div>
                  )}

                  {tab.itemList.map((item, index) => {
                    return (
                      <ChatItem
                        item={item}
                        key={tab.key + "-" + index}
                      ></ChatItem>
                    );
                  })}
                </div>
              </Tabs.Tab>
            );
          })}

          <Tabs.Tab
            title={<AddOutline onClick={addTab} />}
            key={"addBtn"}
          ></Tabs.Tab>
        </Tabs>
      </div>

      <div>
        <Form
          onFinish={send2}
          style={{ "--prefix-width": "2.0em" }}
          layout="horizontal"
          mode="card"
          footer={
            <Button block type="submit" color="primary" size="large">
              提交
            </Button>
          }
        >
          <Form.Item
            name="content"
            label="内容"
            rules={[{ required: true }, { type: "string", min: 1 }]}
          >
            <TextArea
              ref={textRef}
              showCount
              placeholder="请输入内容"
              clearable
              maxLength={200}
              rows={4}
              style={{
                border: "1px solid #ccc",
                borderRadius: "5px",
                padding: "5px",
              }}
            />
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}

function ChatItem(props) {
  const demoAvatarImages = [
    "https://images.unsplash.com/photo-1548532928-b34e3be62fc6?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&fit=crop&h=200&w=200&ixid=eyJhcHBfaWQiOjE3Nzg0fQ",
    "https://images.unsplash.com/photo-1493666438817-866a91353ca9?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&fit=crop&h=200&w=200&s=b616b2c5b373a80ffc9636ba24f7a4a9",
    "https://images.unsplash.com/photo-1542624937-8d1e9f53c1b9?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&fit=crop&h=200&w=200&ixid=eyJhcHBfaWQiOjE3Nzg0fQ",
    "https://images.unsplash.com/photo-1546967191-fdfb13ed6b1e?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&fit=crop&h=200&w=200&ixid=eyJhcHBfaWQiOjE3Nzg0fQ",
  ];
  let { item } = props;
  if (item.type === "left") {
    const leftRet = (
      <div className="chat-item">
        <div className="chat-head">
          <Avatar
            className="chat-head-left"
            src={demoAvatarImages[0]}
            style={{ "--size": "48px" }}
          />
        </div>
        <Card className="chat-text">{item.text}</Card>
        <div className="chat-space"></div>
      </div>
    );

    return leftRet;
  } else if (item.type === "right") {
    const rightRet = (
      <div className="chat-item">
        <div className="chat-space"></div>
        <Card className="chat-text chat-text-right">{item.text}</Card>
        <div className="chat-head">
          <Avatar
            className="chat-head-right"
            src={demoAvatarImages[1]}
            style={{ "--size": "48px" }}
          />
        </div>
      </div>
    );
    return rightRet;
  }
}

export default ZpChat;
